#Conversion of SPC files into a single flat table
#Andrew Sila
#A.sila@cgiar.org
#21.March.2013library(soil.spec)

library(hexView)

#If the library hexView has not been istalled in your computer type the following in your R-console window and run:
#install.packages("hexView",depependencies=TRUE)

#Specify the directory path to where spc files are kept

setwd("~/GRP4/Arusha/Rama_NRM/Rama_NRM March13")
zp<-list.files()

#To standardize the spectral regions to those of ICRAF set wavenumber="ICRAF", otherwise use the default here
raw <- read.spc(getwd(),wavenumber="first.sample")


spec <- raw$spectra
info <- raw$additional.information
colnames(info) <- c("SSN",colnames(info[,-1]))

#Extract the spectrum names and assign them to SSN, check the format of spectral names here. 
#This codes works for spectral filenames prefixed with the first three characters and a space and then charcter 5 to 10 being the #spectrum number e.g "sel 000001" where the space is dropped to obtain "sel000001";

SSN <- c()
for (i in 1:length(info$SSN)){
	ssnl <- nchar(info$SSN[i])
	ssn <- ifelse(ssnl>9,paste(substr(info$SSN[i],1,3),substr(info$SSN[i],5,10),sep=""),info$SSN[i][i])
	SSN <- c(SSN,ssn)
}

info$SSN <- SSN
raws <- cbind(info,spec)
hd <- as.vector(colnames(raws))
w <- which(hd=="Wavebands")
m <- which(hd=="Material")
s <- which(hd=="Spectral_range")

#Write the flat table obtained into a csv or an ascc format.
write.table(raws[,-c(w,m,s)],file="Rama_NRM raw NIR spectra.csv",sep=",",row.names=FALSE)

#The above saves the flat-table into the same directory with spc files.

#To save it in a different folder, specify the working prior to running the last line using: setwd() function

